package code.sbxj.qwd.com.sbxj;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.CacheDiskUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;


@ContentView(R.layout.activity_uploadlist)
public class UploadListActivity extends BaseActivity {

    @ViewInject(R.id.listview)
    private ListView listview;
    @ViewInject(R.id.state1)
    private TextView state1;

    @ViewInject(R.id.state2)
    private TextView state2;

    MyAdapter myadapter;
    JSONArray dataArray = new JSONArray();
    boolean isoffline;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isoffline = (boolean) CacheDiskUtils.getInstance().getSerializable("isoffline", false);
        setTitleText("待上传列表");

        dataArray = CacheDiskUtils.getInstance().getJSONArray("uploaddata");
        if(dataArray==null){
            dataArray=new JSONArray();
        }
        initView();

        state1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(CacheDiskUtils.getInstance().getString("cookie")==null){
                    AlertDialog.Builder normalDialog =
                            new AlertDialog.Builder(UploadListActivity.this);
                    normalDialog.setTitle("温馨提示");
                    normalDialog.setMessage("当前为离线模式，是否立即登录？");
                    normalDialog.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    Intent intent =new Intent();
                                    intent.putExtra("istomain",false);
                                    intent.setClass(UploadListActivity.this, LoginActivity.class);
                                    startActivity(intent);
                                }
                            });
                    normalDialog.setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            });
                    // 显示
                    normalDialog.show();
                    return;
                }

                if(dataArray==null||dataArray.length()==0){
                    return;
                }

                ShowLoading();
                Upload(0);
            }
        });
        state2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CacheDiskUtils.getInstance().remove("uploaddata");
                dataArray=new JSONArray();
                myadapter.notifyDataSetChanged();
            }
        });

    }

    private void Save(final int currentindex) {

        RequestParams params = new RequestParams(Config.BaseUrl + "checkRecord/add");
        params.setAsJsonContent(true);
        params.setUseCookie(true);
        params.addHeader("cookie", CacheDiskUtils.getInstance().getString("cookie"));
        try {
            params.setBodyContent(dataArray.getJSONObject(currentindex).toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    dataArray.getJSONObject(currentindex).put("isuploaded",true);
                    myadapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if(currentindex<(dataArray.length()-1)){
                    Upload(currentindex+1);
                }else{
                    RemoveUploaded();
                    CancleLoading();
                    Toast.makeText(x.app(), " 上传完毕", Toast.LENGTH_LONG).show();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                try {
                    dataArray.getJSONObject(currentindex).put("isuploaded",false);
                    myadapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (ex.toString().contains("不在巡检任务时间")) {
                    Toast.makeText(x.app(), "不在巡检任务时间范围内", Toast.LENGTH_SHORT).show();
                }else if (ex.toString().contains("重复")) {
                    Toast.makeText(x.app(), "重复提交", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_SHORT).show();
                }

                if(currentindex<(dataArray.length()-1)){
                    Upload(currentindex+1);
                }else{
                    RemoveUploaded();
                    CancleLoading();
                    Toast.makeText(x.app(), " 上传完毕", Toast.LENGTH_LONG).show();
                }

            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    void RemoveUploaded(){
        for(int i=0;i<dataArray.length();i++){

            try {
                if(dataArray.getJSONObject(i).optBoolean("isuploaded",false)){
                    dataArray=remove(dataArray,i);
                    i--;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        CacheDiskUtils.getInstance().put("uploaddata",dataArray);
        myadapter.notifyDataSetChanged();

    }
    public JSONArray remove(JSONArray jsonArray,int index){
        JSONArray mJsonArray  = new JSONArray();

        if(index<0)    return mJsonArray;
        if(index>jsonArray.length())   return mJsonArray;

        for( int i=0;i<index;i++){
            try {
                mJsonArray.put(jsonArray.getJSONObject(i));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        for( int i=index+1;i< jsonArray.length();i++){
            try {
                mJsonArray.put(jsonArray.getJSONObject(i));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return mJsonArray;
    }

    private void Upload(final int currentindex) {
        RequestParams params = new RequestParams(Config.BaseUrl + "attachment/upload");
        params.setUseCookie(true);
        params.addHeader("cookie", CacheDiskUtils.getInstance().getString("cookie"));
        try {
            params.addBodyParameter("uuid", dataArray.getJSONObject(currentindex).optString("processAttachId"));
            JSONArray imgarray = dataArray.getJSONObject(currentindex).getJSONArray("imgarray");
            if(imgarray.length()==0){
                Save(currentindex);

                return;
            }
            for (int i=0;i<imgarray.length();i++) {
                params.addBodyParameter("file", new File(imgarray.getString(i)));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Save(currentindex);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    void initView() {
        myadapter = new MyAdapter();
        listview.setAdapter(myadapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });
    }

    class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return dataArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return dataArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            convertView = getLayoutInflater().inflate(R.layout.activity_uploaditerm, null);

            TextView linename = convertView.findViewById(R.id.linename);
            TextView temptv = convertView.findViewById(R.id.temptv);

            try {
                linename.setText("待上传：" + dataArray.getJSONObject(position).optString("name"));
                temptv.setText(dataArray.getJSONObject(position).optBoolean("isuploaded",false)?"已上传":"未上传");

            } catch (JSONException e) {
                e.printStackTrace();
            }

            return convertView;
        }


    }


    private void getTasklist(int lineid) {
        if (isoffline) {

            try {
                dataArray = CacheDiskUtils.getInstance().getJSONObject("offlinedata").getJSONArray("lineCheckPointList");
                myadapter.notifyDataSetChanged();
                return;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        ShowLoading();
        RequestParams params = new RequestParams(Config.BaseUrl + "line/devices?lineId=" + lineid);
        params.setUseCookie(true);
        params.addHeader("cookie", CacheDiskUtils.getInstance().getString("cookie"));
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Log.e("result", result);

                try {
                    dataArray = new JSONArray(result);
                    myadapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                CancleLoading();
            }
        });
    }


}
